﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace NDepot.Validations.Validators
{
    public class EqualToPropertyValidator : ModelValidator
    {
        private readonly string compareProperty;
        public EqualToPropertyValidator(ModelMetadata metadata,
        ControllerContext context, string compareProperty)
            : base(metadata, context)
        {
            this.compareProperty = compareProperty;
        }
        public override IEnumerable<ModelValidationResult> Validate(object container)
        {
            if (Metadata.Model == null)
                yield break;
            var propertyInfo = container.GetType().GetProperty(compareProperty);
            if (propertyInfo == null)
                throw new InvalidOperationException("Unknown property:" + compareProperty);
            var valueToCompare = propertyInfo.GetValue(container, null);
            if (!Metadata.Model.Equals(valueToCompare))
                yield return new ModelValidationResult
                {
                    Message = "This value must equal the value of " + compareProperty
                };
        }
    }
}